﻿using AVCUMPlatform.HelperLibrary;
using Dm;
using Kdbndp;
using MySql.Data.MySqlClient;
using System.Data.Common;

namespace AVCUMPlatform.DAL
{
    /// <summary>
    /// 数据库连接工厂
    /// </summary>
    public class DBConnectionFactory
    {
        /// <summary>
        /// 连接类型
        /// </summary>
        private ConnType connType;
        /// <summary>
        /// 连接字符串
        /// </summary>
        private string connStr;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="_connStr"></param>
        /// <param name="_connType"></param>
        public DBConnectionFactory(string _connStr, ConnType _connType = ConnType.MYSQL)
        {
            connStr = _connStr;
            connType = _connType;
        }

        /// <summary>
        /// 获取连接
        /// </summary>
        /// <returns></returns>
        public DbConnection GetConnection()
        {
            try
            {
                DbConnection dbConnection = null;
                switch (connType)
                {
                    case ConnType.MYSQL:
                        dbConnection = new MySqlConnection(connStr);
                        break;
                    case ConnType.SQLSERVER:
                        throw new Exception("invalid db type");
                    case ConnType.ORACLE:
                        throw new Exception("invalid db type");
                    case ConnType.DM:
                        dbConnection = new DmConnection(connStr);
                        break;
                    case ConnType.RDJC:
                        AppContext.SetSwitch("Kdbndp.EnableLegacyCaseInsensitiveDbParameters", true);
                        dbConnection = new KdbndpConnection(connStr);
                        break;
                    default:
                        throw new Exception("invalid db type");
                }
                dbConnection.Open();
                return dbConnection;
            }
            catch (Exception ex)
            {
                Log.WriteException(ex);
                throw new Exception("数据库连接失败，请联系技术支持");
            }

        }
    }

    /// <summary>
    /// 连接数据库类型
    /// </summary>
    public enum ConnType
    {
        MYSQL,
        SQLSERVER,
        ORACLE,
        DM,
        RDJC
    }
}
